import React, { Component } from 'react'
import Header from './components/Header'
import Main from './components/Main'
import Footer from './components/Footer'

import './index.css'
class App extends Component {
  state = {
    list: [
      {
        id: 1,
        content: 'Taste JavaScript',
        checked: true,
      },
      {
        id: 2,
        content: 'Buy a unicorn',
        checked: false,
      },
    ],
    condition: 'All',
  }
  addContent = (value) => {
    const { list } = this.state
    const listItem = {
      id: Math.random(),
      content: value,
      checked: false,
    }
    this.setState({
      list: [listItem, ...list],
      listItem: {},
    })
  }
  onDel = (id) => {
    const { list } = this.state
    console.log(id)
    if (window.confirm('确定删除吗')) {
      this.setState({
        list: list.filter((item) => item.id !== id),
      })
    }
  }
  changeStatus = (id) => {
    const { list } = this.state
    console.log(id)
    const arr = list.map((item) => {
      if (item.id === id) {
        return {
          ...item,
          checked: !item.checked,
        }
      }
      return item
    })
    this.setState({
      list: arr,
    })
  }
  checkAll = (checked) => {
    console.log(checked)
    this.setState({
      list: this.state.list.map((item) => {
        return {
          ...item,
          checked: checked,
        }
      }),
    })
  }
  showList = (type) => {
    console.log(type)
    this.setState({ condition: type })
  }
  removeComplete = () => {
    this.setState({
      list: this.state.list.filter((item) => !item.checked),
    })
  }
  componentDidMount() {
    const list = JSON.parse(localStorage.getItem('todos') || '[]')
    console.log(list)
    this.setState({ list: list })
  }
  componentDidUpdate() {
    localStorage.setItem('todos', JSON.stringify(this.state.list))
  }

  render() {
    const { list } = this.state
    const leftList = list.filter((item) => !item.checked)

    return (
      <section className="todoapp">
        <Header addContent={this.addContent}></Header>

        <Main
          list={list}
          onDel={this.onDel}
          changeStatus={this.changeStatus}
          checkAll={this.checkAll}
          condition={this.state.condition}
        ></Main>

        <Footer
          leftList={leftList}
          showList={this.showList}
          removeComplete={this.removeComplete}
          condition={this.state.condition}
        ></Footer>
      </section>
    )
  }
}

export default App
